<template>
  <el-dialog
    v-model="dialogVisible"
    title="降雨数据分析"
    width="1200px"
    :close-on-click-modal="false"
  >
    <!-- 分析控制面板 -->
    <el-card class="control-panel" shadow="never">
      <el-form :model="analysisForm" :inline="true" label-width="80px">
        <el-form-item label="分析类型">
          <el-select
            v-model="analysisForm.analysisType"
            placeholder="请选择分析类型"
            style="width: 200px"
            @change="updateAnalysis"
          >
            <el-option label="趋势分析" value="trend" />
            <el-option label="频率分析" value="frequency" />
            <el-option label="强度分析" value="intensity" />
            <el-option label="季节分析" value="seasonal" />
            <el-option label="相关性分析" value="correlation" />
            <el-option label="预测分析" value="prediction" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间粒度">
          <el-select
            v-model="analysisForm.timeGranularity"
            placeholder="请选择时间粒度"
            style="width: 150px"
            @change="updateAnalysis"
          >
            <el-option label="日" value="day" />
            <el-option label="周" value="week" />
            <el-option label="月" value="month" />
            <el-option label="季度" value="quarter" />
            <el-option label="年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="分析指标">
          <el-select
            v-model="analysisForm.metric"
            placeholder="请选择分析指标"
            style="width: 150px"
            @change="updateAnalysis"
          >
            <el-option label="降雨量" value="rainfall" />
            <el-option label="降雨强度" value="intensity" />
            <el-option label="持续时长" value="duration" />
            <el-option label="降雨频次" value="frequency" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateAnalysis">
            <el-icon><Refresh /></el-icon>
            更新分析
          </el-button>
          <el-button type="success" @click="exportAnalysis">
            <el-icon><Download /></el-icon>
            导出报告
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 分析结果展示 -->
    <el-row :gutter="20">
      <!-- 左侧图表区域 -->
      <el-col :span="16">
        <el-card class="chart-container" shadow="never">
          <template #header>
            <span class="panel-title">{{ getAnalysisTitle() }}</span>
          </template>
          <div ref="analysisChartRef" class="analysis-chart" v-loading="analysisLoading"></div>
        </el-card>
      </el-col>

      <!-- 右侧分析结果 -->
      <el-col :span="8">
        <el-card class="analysis-results" shadow="never">
          <template #header>
            <span class="panel-title">分析结果</span>
          </template>
          <div class="result-content">
            <div class="result-section">
              <h4>关键指标</h4>
              <div class="metric-list">
                <div class="metric-item" v-for="metric in keyMetrics" :key="metric.label">
                  <span class="metric-label">{{ metric.label }}：</span>
                  <span class="metric-value">{{ metric.value }}</span>
                </div>
              </div>
            </div>

            <div class="result-section">
              <h4>趋势分析</h4>
              <div class="trend-analysis">
                <div class="trend-item">
                  <el-icon :color="trendAnalysis.trend === 'up' ? '#67c23a' : trendAnalysis.trend === 'down' ? '#f56c6c' : '#e6a23c'">
                    <component :is="getTrendIcon()" />
                  </el-icon>
                  <span>{{ trendAnalysis.description }}</span>
                </div>
                <div class="trend-detail">
                  变化幅度：{{ trendAnalysis.changeRate }}
                </div>
              </div>
            </div>

            <div class="result-section">
              <h4>异常检测</h4>
              <div class="anomaly-list">
                <div class="anomaly-item" v-for="anomaly in anomalies" :key="anomaly.id">
                  <el-tag :type="anomaly.level === 'high' ? 'danger' : anomaly.level === 'medium' ? 'warning' : 'info'">
                    {{ anomaly.type }}
                  </el-tag>
                  <span class="anomaly-desc">{{ anomaly.description }}</span>
                </div>
              </div>
            </div>

            <div class="result-section">
              <h4>预测结果</h4>
              <div class="prediction-results">
                <div class="prediction-item">
                  <span class="prediction-label">下月预测：</span>
                  <span class="prediction-value">{{ prediction.nextMonth }}</span>
                </div>
                <div class="prediction-item">
                  <span class="prediction-label">置信度：</span>
                  <span class="prediction-value">{{ prediction.confidence }}%</span>
                </div>
                <div class="prediction-item">
                  <span class="prediction-label">风险等级：</span>
                  <el-tag :type="getRiskTagType(prediction.riskLevel)">
                    {{ prediction.riskLevel }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细分析表格 -->
    <el-card class="analysis-table" shadow="never">
      <template #header>
        <span class="panel-title">详细分析数据</span>
      </template>
      <el-table :data="analysisTableData" stripe border max-height="300">
        <el-table-column prop="period" label="时间周期" width="120" />
        <el-table-column prop="count" label="降雨次数" width="100" />
        <el-table-column prop="totalRainfall" label="总降雨量(mm)" width="120" />
        <el-table-column prop="avgRainfall" label="平均降雨量(mm)" width="130" />
        <el-table-column prop="maxRainfall" label="最大降雨量(mm)" width="130" />
        <el-table-column prop="avgIntensity" label="平均强度(mm/h)" width="120" />
        <el-table-column prop="maxIntensity" label="最大强度(mm/h)" width="120" />
        <el-table-column prop="typicalRate" label="典型降雨率(%)" width="120" />
        <el-table-column prop="trend" label="趋势" width="100">
          <template #default="{ row }">
            <el-icon :color="row.trend === 'up' ? '#67c23a' : row.trend === 'down' ? '#f56c6c' : '#e6a23c'">
              <component :is="getTrendIcon(row.trend)" />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download, TrendCharts, ArrowUp, ArrowDown, Minus } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

interface Props {
  visible: boolean
  analysisData?: any[]
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  analysisData: () => []
})

const emit = defineEmits<Emits>()

const analysisChartRef = ref<HTMLDivElement>()
const analysisChartInstance = ref<echarts.ECharts>()
const analysisLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 分析表单
const analysisForm = reactive({
  analysisType: 'trend',
  timeGranularity: 'month',
  metric: 'rainfall'
})

// 关键指标
const keyMetrics = ref([
  { label: '总降雨量', value: '1256.8 mm' },
  { label: '平均降雨量', value: '27.9 mm' },
  { label: '最大降雨量', value: '125.3 mm' },
  { label: '降雨天数', value: '45 天' },
  { label: '典型降雨率', value: '68.9%' },
  { label: '变异系数', value: '0.85' }
])

// 趋势分析
const trendAnalysis = reactive({
  trend: 'up',
  description: '降雨量呈上升趋势',
  changeRate: '+15.2%'
})

// 异常检测
const anomalies = ref([
  { id: 1, type: '极值异常', level: 'high', description: '2024-01-08 降雨量异常偏高' },
  { id: 2, type: '频次异常', level: 'medium', description: '1月份降雨频次高于历史平均' },
  { id: 3, type: '强度异常', level: 'low', description: '部分降雨强度波动较大' }
])

// 预测结果
const prediction = reactive({
  nextMonth: '180-220 mm',
  confidence: 85,
  riskLevel: '中等风险'
})

// 分析表格数据
const analysisTableData = ref([
  {
    period: '2024-01',
    count: 12,
    totalRainfall: 385.6,
    avgRainfall: 32.1,
    maxRainfall: 125.3,
    avgIntensity: 18.5,
    maxIntensity: 45.8,
    typicalRate: 75.0,
    trend: 'up'
  },
  {
    period: '2023-12',
    count: 8,
    totalRainfall: 245.2,
    avgRainfall: 30.7,
    maxRainfall: 85.6,
    avgIntensity: 16.2,
    maxIntensity: 32.5,
    typicalRate: 62.5,
    trend: 'stable'
  },
  {
    period: '2023-11',
    count: 15,
    totalRainfall: 425.8,
    avgRainfall: 28.4,
    maxRainfall: 95.2,
    avgIntensity: 20.1,
    maxIntensity: 38.7,
    typicalRate: 66.7,
    trend: 'down'
  }
])

// 获取分析标题
const getAnalysisTitle = () => {
  const typeMap = {
    trend: '趋势分析图',
    frequency: '频率分析图',
    intensity: '强度分析图',
    seasonal: '季节分析图',
    correlation: '相关性分析图',
    prediction: '预测分析图'
  }
  return typeMap[analysisForm.analysisType] || '分析图表'
}

// 获取趋势图标
const getTrendIcon = (trend?: string) => {
  const trendValue = trend || trendAnalysis.trend
  switch (trendValue) {
    case 'up':
      return ArrowUp
    case 'down':
      return ArrowDown
    default:
      return Minus
  }
}

// 获取风险等级标签类型
const getRiskTagType = (level: string) => {
  const levelMap = {
    '低风险': 'success',
    '中等风险': 'warning',
    '高风险': 'danger',
    '极高风险': 'danger'
  }
  return levelMap[level] || 'info'
}

// 初始化分析图表
const initAnalysisChart = () => {
  if (!analysisChartRef.value) return
  
  analysisChartInstance.value = echarts.init(analysisChartRef.value)
  updateAnalysis()
}

// 更新分析
const updateAnalysis = () => {
  if (!analysisChartInstance.value) return
  
  analysisLoading.value = true
  
  setTimeout(() => {
    const option = getAnalysisChartOption()
    analysisChartInstance.value?.setOption(option, true)
    updateAnalysisResults()
    analysisLoading.value = false
  }, 500)
}

// 获取分析图表配置
const getAnalysisChartOption = () => {
  switch (analysisForm.analysisType) {
    case 'trend':
      return getTrendAnalysisOption()
    case 'frequency':
      return getFrequencyAnalysisOption()
    case 'intensity':
      return getIntensityAnalysisOption()
    case 'seasonal':
      return getSeasonalAnalysisOption()
    case 'correlation':
      return getCorrelationAnalysisOption()
    case 'prediction':
      return getPredictionAnalysisOption()
    default:
      return getTrendAnalysisOption()
  }
}

// 趋势分析图配置
const getTrendAnalysisOption = () => {
  return {
    title: {
      text: '降雨量趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['实际值', '趋势线', '预测值']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '降雨量(mm)'
    },
    series: [
      {
        name: '实际值',
        type: 'line',
        data: [385, 245, 425, 320, 280, 450, 520, 380, 290, 350, 420, 380],
        itemStyle: { color: '#409eff' }
      },
      {
        name: '趋势线',
        type: 'line',
        data: [350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460],
        lineStyle: { type: 'dashed' },
        itemStyle: { color: '#67c23a' }
      },
      {
        name: '预测值',
        type: 'line',
        data: [null, null, null, null, null, null, null, null, null, null, null, 460, 470, 480],
        lineStyle: { type: 'dotted' },
        itemStyle: { color: '#e6a23c' }
      }
    ]
  }
}

// 频率分析图配置
const getFrequencyAnalysisOption = () => {
  return {
    title: {
      text: '降雨频率分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['0-10mm', '10-25mm', '25-50mm', '50-100mm', '100-250mm', '>250mm']
    },
    yAxis: {
      type: 'value',
      name: '频次'
    },
    series: [{
      name: '频次',
      type: 'bar',
      data: [15, 20, 12, 8, 3, 1],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      }
    }]
  }
}

// 强度分析图配置
const getIntensityAnalysisOption = () => {
  return {
    title: {
      text: '降雨强度分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: [
        { name: '小雨', max: 100 },
        { name: '中雨', max: 100 },
        { name: '大雨', max: 100 },
        { name: '暴雨', max: 100 },
        { name: '大暴雨', max: 100 },
        { name: '特大暴雨', max: 100 }
      ]
    },
    series: [{
      name: '降雨强度分布',
      type: 'radar',
      data: [
        {
          value: [85, 70, 60, 45, 25, 10],
          name: '强度分布'
        }
      ]
    }]
  }
}

// 季节分析图配置
const getSeasonalAnalysisOption = () => {
  return {
    title: {
      text: '季节性降雨分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['春季', '夏季', '秋季', '冬季']
    },
    xAxis: {
      type: 'category',
      data: ['3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月', '1月', '2月']
    },
    yAxis: {
      type: 'value',
      name: '降雨量(mm)'
    },
    series: [
      {
        name: '月降雨量',
        type: 'bar',
        data: [320, 280, 450, 520, 380, 290, 350, 420, 380, 245, 385, 425],
        itemStyle: {
          color: (params) => {
            const colors = ['#91cc75', '#fac858', '#ee6666', '#73c0de']
            const seasonIndex = Math.floor(params.dataIndex / 3) % 4
            return colors[seasonIndex]
          }
        }
      }
    ]
  }
}

// 相关性分析图配置
const getCorrelationAnalysisOption = () => {
  return {
    title: {
      text: '降雨量与强度相关性分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        return `降雨量: ${params.value[0]}mm<br/>强度: ${params.value[1]}mm/h`
      }
    },
    xAxis: {
      type: 'value',
      name: '降雨量(mm)'
    },
    yAxis: {
      type: 'value',
      name: '强度(mm/h)'
    },
    series: [{
      name: '相关性',
      type: 'scatter',
      data: [
        [15.8, 8.5], [28.7, 15.2], [45.2, 18.3], [85.6, 32.5], [125.3, 45.8]
      ],
      symbolSize: 10,
      itemStyle: {
        color: '#409eff'
      }
    }]
  }
}

// 预测分析图配置
const getPredictionAnalysisOption = () => {
  return {
    title: {
      text: '降雨量预测分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['历史数据', '预测数据', '置信区间']
    },
    xAxis: {
      type: 'category',
      data: ['10月', '11月', '12月', '1月', '2月', '3月', '4月', '5月']
    },
    yAxis: {
      type: 'value',
      name: '降雨量(mm)'
    },
    series: [
      {
        name: '历史数据',
        type: 'line',
        data: [350, 420, 380, 385, 245, null, null, null],
        itemStyle: { color: '#409eff' }
      },
      {
        name: '预测数据',
        type: 'line',
        data: [null, null, null, 385, 245, 320, 280, 350],
        lineStyle: { type: 'dashed' },
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
}

// 更新分析结果
const updateAnalysisResults = () => {
  // 根据分析类型更新关键指标和结果
  // 这里可以根据实际数据进行计算
}

// 导出分析报告
const exportAnalysis = () => {
  ElMessage.success('正在导出分析报告...')
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

// 监听弹窗显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    nextTick(() => {
      initAnalysisChart()
    })
  }
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (analysisChartInstance.value) {
    analysisChartInstance.value.dispose()
  }
})
</script>

<style scoped>
.control-panel {
  margin-bottom: 20px;
}

.chart-container {
  height: 450px;
}

.analysis-chart {
  width: 100%;
  height: 400px;
}

.analysis-results {
  height: 450px;
  overflow-y: auto;
}

.panel-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.result-content {
  padding: 10px 0;
}

.result-section {
  margin-bottom: 20px;
}

.result-section h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.metric-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
}

.metric-label {
  font-size: 12px;
  color: #666;
}

.metric-value {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.trend-analysis {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.trend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.trend-detail {
  font-size: 12px;
  color: #666;
  margin-left: 24px;
}

.anomaly-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.anomaly-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.anomaly-desc {
  font-size: 12px;
  color: #666;
  flex: 1;
}

.prediction-results {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.prediction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.prediction-label {
  font-size: 12px;
  color: #666;
}

.prediction-value {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.analysis-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>